package com.dcy.daily.skill.rabbitMQ.springAMQP.tmp.batch;

import com.dcy.daily.common.config.annotation.ComponentUtil;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.batch.BatchingStrategy;
import org.springframework.amqp.rabbit.batch.SimpleBatchingStrategy;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.BatchingRabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;


/**
 * 批量发送与监听
 * @author duanchunyu
 * @version 1.0.0
 * @createTime 2021年07月22日 11:10
 */
@ComponentUtil.UComponent
public class RabbitMqConfig {

    @Bean
    public Queue myQueue() {
        return new Queue("myqueue");
    }


    /**
     * MQ连接工厂
     * @return
     */
    @Bean
    CachingConnectionFactory ccf() {
        CachingConnectionFactory ccf = new CachingConnectionFactory();
        ccf.setHost("centos-node-135");
        ccf.setUsername("guest");
        ccf.setPassword("guest");
        ccf.setPort(5672);
        return ccf;
    }

    @Bean
    public SimpleRabbitListenerContainerFactory consumerBatchContainerFactory(CachingConnectionFactory ccf) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(ccf);
        factory.setBatchListener(true); // configures a BatchMessageListenerAdapter
        factory.setBatchSize(2);
        factory.setConsumerBatchEnabled(true);
        return factory;
    }

    @Bean("batchQueueTaskScheduler")
    public TaskScheduler batchQueueTaskScheduler(){
        TaskScheduler taskScheduler=new ThreadPoolTaskScheduler();
        return taskScheduler;
    }

    @Bean
    public BatchingRabbitTemplate batchingRabbitTemplate(CachingConnectionFactory ccf,TaskScheduler batchQueueTaskScheduler){
        int batchSize = 10;
        int bufferLimit = 1024;
        long timeout = 10000;
        BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(batchSize,bufferLimit,timeout);
        BatchingRabbitTemplate batchingRabbitTemplate = new BatchingRabbitTemplate(ccf,batchingStrategy,batchQueueTaskScheduler);
        return batchingRabbitTemplate;
    }
}
